// pages/orders/orders.ts
import { MerchantAPI } from '../../utils/api'

interface Order {
  orderId: number;
  orderNo: string;
  orderTime: string;
  status: number;
  statusText: string;
  finalAmountRange: string;
  remark: string;
  pickupCode: string;
  customer: {
    userId: number;
    nickname: string;
    phoneNumber: string;
  };
  items?: OrderItem[];
  totalAmount?: number;
  deliveryTime?: string;
  itemCount?: number;
}

interface OrderItem {
  product_id: number;
  product_name: string;
  price: number;
  quantity: number;
  image_url: string;
}

interface OrderDetail {
  order_id: string;
  status: string;
  created_at: string;
  payment_method: string;
  total_amount: number;
  packing_fee: number;
  delivery_fee: number;
  discount: number;
  expected_income: number;
  user_info: {
    name: string;
    phone: string;
    address: string;
    delivery_time: string;
    delivery_type: string;
  };
  items: OrderItem[];
  actions: Array<{
    type: string;
    label: string;
    disabled: boolean;
  }>;
}

interface OrdersPageData {
  hasLogin: boolean;
  activeTab: string;
  activeTabText: string;
  refreshing: boolean;
  loading: boolean;
  showSearch: boolean;
  searchKeyword: string;
  orders: Order[];
  filteredOrders: Order[];
  page: number;
  pageSize: number;
  hasMore: boolean;
  total: number;
  
  // 订单详情
  showDetailModal: boolean;
  orderDetail: OrderDetail | null;
  
  // 联系用户
  showContactModal: boolean;
  contactInfo: any;
  selectedContactType: number;
  contactNotes: string;
  
  // 状态栏高度
  statusBarHeight: number;
  navBarHeight: number;
}

Page({
  data: {
    hasLogin: false,
    activeTab: 'all', // all, pending, preparing, delivering, completed, aftersale
    activeTabText: '全部',
    refreshing: false,
    loading: false,
    showSearch: false,
    searchKeyword: '',
    orders: [],
    filteredOrders: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    total: 0,
    
    // 订单详情
    showDetailModal: false,
    orderDetail: null,
    
    // 联系用户
    showContactModal: false,
    contactInfo: null,
    selectedContactType: 1, // 1-电话联系，2-消息联系
    contactNotes: '',
    
    // 状态栏高度
    statusBarHeight: 0,
    navBarHeight: 0
  } as OrdersPageData,

  onLoad() {
    // 获取系统信息，设置状态栏高度
    // 注意：getSystemInfoSync已被弃用，但新API在某些环境中可能不可用，此警告可以忽略
    const systemInfo = wx.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    const navBarHeight = statusBarHeight + 44; // 44是导航栏内容区域的高度
    
    this.setData({
      statusBarHeight,
      navBarHeight
    });
    
    this.checkLoginStatus();
  },

  onShow() {
    this.checkLoginStatus();
    if (this.data.hasLogin) {
      this.refreshData();
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('merchantToken');
    const userInfo = wx.getStorageSync('merchantUserInfo');
    
    if (token && userInfo) {
      this.setData({
        hasLogin: true
      });
    } else {
      this.setData({
        hasLogin: false
      });
    }
  },

  // 模拟登录
  mockLogin() {
    const mockUserInfo = {
      merchantId: 1001,
      merchantName: '绿意轻食',
      contactPerson: '张经理',
      contactPhone: '138****8000',
      status: 1
    };
    
    wx.setStorageSync('merchantToken', 'mock_token_123456');
    wx.setStorageSync('merchantUserInfo', mockUserInfo);
    
    this.setData({
      hasLogin: true
    });
    
    wx.showToast({
      title: '登录成功',
      icon: 'success'
    });
    
    this.refreshData();
  },

  /**
   * 刷新页面数据
   */
  async refreshData() {
    try {
      await this.loadOrders(true);
    } catch (error) {
      console.error('刷新数据失败', error);
    }
  },

  /**
   * 映射标签到订单状态
   */
  mapTabToStatus(tab: string): number | undefined {
    const statusMap: Record<string, number> = {
      pending: 0,      // 待接单
      preparing: 1,    // 已接单
      delivering: 2,   // 制作中
      completed: 3,    // 待取餐
      aftersale: 4     // 已完成（待售后可能对应其他状态）
    };
    return statusMap[tab];
  },

  /**
   * 映射订单状态到文本
   */
  mapStatusToText(status: number): string {
    const statusMap: Record<number, string> = {
      0: '待接单',
      1: '已接单',
      2: '制作中',
      3: '待取餐',
      4: '已完成',
      5: '已取消'
    };
    return statusMap[status] || '未知状态';
  },

  /**
   * 加载订单列表 - 对应接口 /merchant/order/list
   */
  async loadOrders(reset = false) {
    if (reset) {
      this.setData({ page: 1, hasMore: true });
    }

    const { page, pageSize, activeTab } = this.data;

    this.setData({ loading: true });

    try {
      // 构建请求参数，只包含有值的参数
      const params: any = {
        pageNum: page,
        pageSize: pageSize
      };
      
      // 只有在不是"全部"时才添加status参数
      if (activeTab !== 'all') {
        const status = this.mapTabToStatus(activeTab);
        if (status !== undefined) {
          params.status = status;
        }
      }
      
      console.log('请求订单列表参数:', params);
      
      // 调用后端API：/merchant/order/list
      const result = await MerchantAPI.getOrderListNew(params);
      
      console.log('订单列表返回结果:', result);
      
      if (result && result.rows) {
        // 转换后端数据格式到前端格式
        const orders: Order[] = result.rows.map((item: any) => {
          // 计算商品数量
          const itemCount = item.itemCount || (item.items && item.items.length) || 0;
          
          return {
            orderId: item.orderId,
            orderNo: item.orderNo,
            orderTime: item.createdAt || new Date().toLocaleString(),
            status: item.status,
            statusText: this.mapStatusToText(item.status),
            finalAmountRange: `¥${(item.finalAmount || 0).toFixed(2)}`,
            remark: item.remark || '',
            pickupCode: item.pickupCode || '',
            deliveryTime: item.estimatedReadyMin ? `${item.estimatedReadyMin}分钟送达` : '',
            customer: {
              userId: item.customerId,
              nickname: '用户' + item.customerId,
              phoneNumber: '***'
            },
            items: item.items || [],
            totalAmount: item.totalAmount || item.finalAmount || 0,
            itemCount: itemCount
          };
        });
        
        const newOrders = reset ? orders : [...this.data.orders, ...orders];
        
        this.setData({
          orders: newOrders,
          hasMore: orders.length >= pageSize,
          page: reset ? 2 : page + 1,
          total: result.total || 0
        });
        
        this.filterOrders();
      } else {
        // 没有数据
        this.setData({
          orders: [],
          hasMore: false,
          total: 0
        });
        this.filterOrders();
      }

    } catch (error) {
      console.error('加载订单失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      
      // 清空订单列表
      this.setData({
        orders: [],
        hasMore: false
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 切换标签页
   */
  switchTab(e: any) {
    const tab = e.currentTarget.dataset.tab;
    const tabTexts: Record<string, string> = {
      all: '全部',
      pending: '待确认',
      preparing: '待制作',
      delivering: '待配送',
      completed: '已送达',
      aftersale: '待售后'
    };
    
    this.setData({
      activeTab: tab,
      activeTabText: tabTexts[tab]
    });
    
    // 重新加载对应状态的订单
    this.loadOrders(true);
  },

  /**
   * 切换搜索框显示状态
   */
  toggleSearch() {
    const showSearch = !this.data.showSearch;
    this.setData({ 
      showSearch,
      searchKeyword: showSearch ? this.data.searchKeyword : ''
    });
    
    if (!showSearch) {
      this.filterOrders();
    }
  },

  /**
   * 搜索输入处理
   */
  onSearchInput(e: any) {
    const searchKeyword = e.detail.value;
    this.setData({ searchKeyword });
    this.filterOrders();
  },

  /**
   * 过滤订单列表
   */
  filterOrders() {
    const { orders, searchKeyword } = this.data;
    let filteredOrders = orders;
    
    // 按搜索关键词筛选
    if (searchKeyword.trim()) {
      filteredOrders = filteredOrders.filter(order => {
        const keyword = searchKeyword.toLowerCase();
        return order.orderNo.toLowerCase().includes(keyword) ||
          (order.customer?.nickname && order.customer.nickname.toLowerCase().includes(keyword)) ||
          (order.customer?.phoneNumber && order.customer.phoneNumber.includes(keyword));
      });
    }
    
    this.setData({ filteredOrders });
  },

  /**
   * 查看订单详情
   */
  async viewOrderDetail(e: any) {
    const order = e.currentTarget.dataset.order;
    
    try {
      // 调用后端API：/merchant/order/{orderId}
      const response = await MerchantAPI.getOrderDetailNew(order.orderId);
      
      console.log('订单详情返回:', response);
      
      if (response && response.data) {
        const item = response.data;
        
        // 构建详情数据
        const orderDetail: any = {
          orderId: item.orderId,
          orderNo: item.orderNo,
          orderTime: item.createdAt || order.orderTime,
          status: item.status,
          statusText: this.mapStatusToText(item.status),
          items: item.items || [],
          totalAmount: item.totalAmount || 0,
          packingFee: 0,
          deliveryFee: 0,
          discount: item.discountAmount || 0,
          expectedIncome: item.finalAmount || 0,
          customerName: '用户' + item.customerId,
          customerPhone: '***',
          address: item.addressSnapshot || "地址信息",
          deliveryTime: item.estimatedReadyMin ? `预计${item.estimatedReadyMin}分钟` : "尽快送达",
          deliveryType: "外卖配送",
          paymentMethod: item.paymentMethod === 1 ? "微信支付" : item.paymentMethod === 2 ? "余额支付" : "在线支付",
          remark: item.remark || '',
          pickupCode: item.pickupCode || ''
        };
        
        this.setData({
          showDetailModal: true,
          orderDetail: orderDetail
        });
      } else {
        throw new Error('订单详情获取失败');
      }
      
    } catch (error) {
      console.error('获取订单详情失败', error);
      
      wx.showToast({
        title: '获取详情失败',
        icon: 'none'
      });
    }
  },
  
  /**
   * 从详情弹窗确认订单
   */
  confirmOrderDetail(e: any) {
    this.closeDetailModal();
    this.acceptOrder(e);
  },

  /**
   * 确认订单 - 对应接口 /merchant/order/accept/{orderId}
   */
  async acceptOrder(e: any) {
    const orderId = e.currentTarget.dataset.id;
    
    try {
      // 调用后端API：/merchant/order/accept/{orderId}
      await MerchantAPI.acceptOrderNew(orderId, { estimatedMin: 15 });
      
      this.updateLocalOrderStatus(orderId, 1, '已接单');
      
      wx.showToast({
        title: '订单已接单',
        icon: 'success'
      });
      
      // 刷新订单列表
      this.refreshData();
      
    } catch (error: any) {
      console.error('接单失败', error);
      
      wx.showToast({
        title: error.msg || '接单失败',
        icon: 'none'
      });
    }
  },

  /**
   * 开始制作 - 对应接口 /merchant/order/start-making/{orderId}
   */
  async startPreparing(e: any) {
    const orderId = e.currentTarget.dataset.id;
    
    try {
      // 调用后端API：/merchant/order/start-making/{orderId}
      await MerchantAPI.startMaking(orderId);
      
      this.updateLocalOrderStatus(orderId, 2, '制作中');
      
      wx.showToast({
        title: '制作中',
        icon: 'success'
      });
      
      // 刷新订单列表
      this.refreshData();
      
    } catch (error: any) {
      console.error('开始制作失败', error);
      
      wx.showToast({
        title: error.msg || '操作失败',
        icon: 'none'
      });
    }
  },

  /**
   * 制作完成 - 对应接口 /merchant/order/ready/{orderId}
   */
  async readyForPickup(e: any) {
    const orderId = e.currentTarget.dataset.id;
    
    try {
      // 调用后端API：/merchant/order/ready/{orderId}
      await MerchantAPI.orderReady(orderId);
      
      this.updateLocalOrderStatus(orderId, 3, '待取餐');
      
      wx.showToast({
        title: '订单已备餐完成，请通知用户取餐',
        icon: 'success'
      });
      
      // 刷新订单列表
      this.refreshData();
      
    } catch (error: any) {
      console.error('制作完成失败', error);
      
      wx.showToast({
        title: error.msg || '操作失败',
        icon: 'none'
      });
    }
  },

  /**
   * 取消订单 - 对应接口 /merchant/order/cancel
   */
  rejectOrder(e: any) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '取消订单',
      content: '确定要取消这个订单吗？',
      editable: true,
      placeholderText: '请输入取消原因',
      success: async (res) => {
        if (res.confirm) {
          const cancelReason = res.content || '商家暂时无法接单';
          
          if (!cancelReason.trim()) {
            wx.showToast({
              title: '请输入取消原因',
              icon: 'none'
            });
            return;
          }
          
          try {
            // 调用后端API：/merchant/order/cancel
            await MerchantAPI.cancelOrderNew({ 
              orderId, 
              cancelReason: cancelReason
            });
            
            this.updateLocalOrderStatus(orderId, 5, '已取消');
            
            wx.showToast({
              title: '订单已取消',
              icon: 'success'
            });
            
            // 刷新订单列表
            this.refreshData();
            
          } catch (error: any) {
            console.error('取消订单失败', error);
            
            wx.showToast({
              title: error.msg || '取消订单失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  /**
   * 联系用户
   */
  async contactCustomer(e: any) {
    const order = e.currentTarget.dataset.order || this.getOrderFromId(e.currentTarget.dataset.id);
    
    try {
      // 调用后端API：/merchant/orders/{orderId}/contact-info
      // const response = await MerchantAPI.getOrderContactInfo(order.orderId);
      
      // 模拟联系信息
      const mockContactInfo = {
        orderInfo: {
          orderId: order.orderNo,
          orderTime: order.orderTime,
          status: order.status,
          statusText: order.statusText,
          deliveryTime: order.deliveryTime
        },
        contactInfo: {
          contactName: order.customer.nickname,
          contactPhone: order.customer.phoneNumber,
          maskedPhone: order.customer.phoneNumber,
          originalPhone: order.customer.phoneNumber.replace(/\*/g, '1')
        },
        orderItems: [
          {
            productName: "香辣鸡腿堡套餐",
            quantity: 1,
            price: 39.90
          }
        ],
        totalAmount: order.totalAmount || 44.90,
        remark: order.remark
      };
      
      this.setData({
        showContactModal: true,
        contactInfo: mockContactInfo
      });
      
    } catch (error) {
      console.error('获取联系信息失败', error);
      
      // 直接拨打电话
      this.makePhoneCall(order.customer.phoneNumber);
    }
  },

  /**
   * 拨打电话
   */
  makePhoneCall(phone: string) {
    wx.showModal({
      title: '联系客户',
      content: `是否拨打客户电话：${phone}`,
      success: (res) => {
        if (res.confirm) {
          // 记录联系操作
          this.recordContactAction(1, 1, '电话联系客户');
          
          wx.makePhoneCall({
            phoneNumber: phone.replace(/\*/g, '1'), // 模拟完整手机号
            fail: () => {
              wx.showToast({
                title: '拨打失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  /**
   * 记录联系操作 - 对应接口 /merchant/orders/{orderId}/contact-record
   */
  async recordContactAction(contactType: number, contactResult: number, notes: string) {
    try {
      // 调用后端API记录联系操作
      // await MerchantAPI.recordContactAction({
      //   orderId: this.data.contactInfo?.orderInfo?.orderId,
      //   contactType,
      //   contactResult,
      //   contactNotes: notes
      // });
      
      console.log('联系记录已保存');
      
    } catch (error) {
      console.error('记录联系操作失败', error);
    }
  },

  /**
   * 根据ID获取订单
   */
  getOrderFromId(orderId: number): Order | null {
    return this.data.orders.find(order => order.orderId === orderId) || null;
  },

  /**
   * 更新本地订单状态
   */
  updateLocalOrderStatus(orderId: number, status: number, statusText: string) {
    const orders = this.data.orders.map(order => {
      if (order.orderId === orderId) {
        return {
          ...order,
          status,
          statusText
        };
      }
      return order;
    });
    
    this.setData({ orders });
    this.filterOrders();
  },

  /**
   * 显示手动接单
   */
  showManualOrder() {
    wx.showToast({
      title: '手动接单功能开发中',
      icon: 'none'
    });
  },

  /**
   * 下拉刷新
   */
  async onRefresh() {
    this.setData({ refreshing: true });
    
    try {
      await this.refreshData();
    } finally {
      this.setData({ refreshing: false });
    }
  },

  // 弹窗控制
  closeDetailModal() {
    this.setData({
      showDetailModal: false
    });
  },

  closeContactModal() {
    this.setData({
      showContactModal: false,
      contactNotes: ''
    });
  },

  // 联系方式选择
  onContactTypeChange(e: any) {
    this.setData({
      selectedContactType: parseInt(e.detail.value)
    });
  },

  onContactNotesInput(e: any) {
    this.setData({
      contactNotes: e.detail.value
    });
  },

  // 确认联系
  confirmContact() {
    const { contactInfo, selectedContactType, contactNotes } = this.data;
    
    if (selectedContactType === 1) {
      // 电话联系
      this.makePhoneCall(contactInfo.contactInfo.originalPhone);
    } else {
      // 消息联系
      wx.showToast({
        title: '消息发送功能开发中',
        icon: 'none'
      });
    }
    
    this.recordContactAction(selectedContactType, 1, contactNotes);
    this.closeContactModal();
  },

  /**
   * 打印订单
   */
  async printOrder(e: any) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.showLoading({ title: '打印中...' });
    
    try {
      // 调用后端API：/merchant/order/print/{orderId}
      await MerchantAPI.printOrder(orderId);
      
      wx.hideLoading();
      wx.showToast({
        title: '打印成功',
        icon: 'success'
      });
      
    } catch (error: any) {
      wx.hideLoading();
      wx.showToast({
        title: error.msg || '打印失败',
        icon: 'none'
      });
    }
  },

  preventClose() {
    // 阻止事件冒泡
  }
});